package com.alibaba.org.service.impl;


import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.basic.util.MD5Utils;
import com.alibaba.basic.util.StrUtils;
import com.alibaba.org.domain.Employee;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.org.service.IEmployeeService;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Resource
    private LogininfoMapper logininfoMapper;
    @Resource
    private EmployeeMapper employeeMapper;
    /**
     * 重构方法是为了服务controller的
     * 重构save方法
     * @param employee
     */
    @Override
    public void add(Employee employee) {
        // 获取随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);

        employee.setLogininfo_id(logininfo.getId());
        super.add(employee);
    }


    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        // 设为管理员
        logininfo.setType(0);
        return logininfo;
    }

    /**
     * 重构方法是为了服务controller的
     * 重构 删除
     * @param id
     * @return
     */
    @Override
    public void del(Long id) {
        Employee employee =  employeeMapper.loadById(id);
        // 删除登录信息表数据
        logininfoMapper.remove(employee.getLogininfo_id());
        // 删除employee表数据
        super.del(id);
    }

    /**
     * 重构方法是为了服务controller的
     * 重构修改方法
     * @param employee
     */
    @Override
    public void update(Employee employee) {
        // 获取新的随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        Long logininfo_id = employeeMapper.loadById(employee.getId()).getLogininfo_id();
        Logininfo logininfo = employee2Logininfo(employee);
        // 需要找到数据库中对应id的对象修改
        logininfo.setId(logininfo_id);
        logininfoMapper.update(logininfo);
        super.update(employee);
    }
}
